Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]]
Given target = 3, return true.
题目大意:给定一个递增矩阵(没一行从左到右递增,下一行第一个数大于上一行最后一个数,判断一个数是否存在于矩阵中)
题目难度:Medium
/**
* Created by gzdaijie on 16/5/30
* 先找到最大的x,如果target存在,target必然在Row x中
* 然后再找到Col y
* 时间复杂度O(M + N),空间复杂度O(1)
*/
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) return false;
if (matrix[0].length == 0) return false;
int m = matrix.length;
int n = matrix[0].length;
int x = 0, y = 0;
while (x < m - 1 && matrix[x + 1][y] <= target) x++;
while (y < n - 1 && matrix[x][y + 1] <= target) y++;
return matrix[x][y] == target;
}
}